const jwt = require("jsonwebtoken");
const md5 = require("md5");
const { loginDao, updateAdminDao } = require("../dao/adminDao");
const { ValidationError, UnknownError } = require("../utils/errors");
const { formatResponseBody } = require("../utils/tools")

// 登录业务
exports.login = async function (userInfo, res) {
    // 将密码进行加密后重新赋值
    userInfo.loginPwd = md5(userInfo.loginPwd);

    try {
        const { dataValues } = await loginDao(userInfo);

        // 删除密码字段
        delete dataValues.loginPwd;

        // 确定过期时间
        const expTime = userInfo.remember || 1;
        // 添加token
        const token = jwt.sign(dataValues, md5(process.env.JWT_SECURE), { expiresIn: 60 * 60 * 24 * expTime });

        res.set("authentication", token);

        return formatResponseBody({ data: dataValues });
    } catch (err) {
        throw new ValidationError("账号或密码错误");
    }
}

// 修改管理员信息业务
exports.changeAdminService = async function (newUserinfo, id) {
    // 判断新旧密码是否相同
    if (newUserinfo.oldLoginPwd === newUserinfo.loginPwd) {
        throw new ValidationError("新旧密码一致");
    }

    // 1. 将新旧密码进行md5加密
    newUserinfo.oldLoginPwd = md5(newUserinfo.oldLoginPwd);
    newUserinfo.loginPwd = md5(newUserinfo.loginPwd);

    // 2. 验证旧密码是否正确
    const loginResult = await loginDao({
        loginId: newUserinfo.loginId,
        loginPwd: newUserinfo.oldLoginPwd
    });

    // 进入此if证明旧密码没错
    if (loginResult) {
        const result = await updateAdminDao({
            name: newUserinfo.name,
            loginPwd: newUserinfo.loginPwd,
        }, id);

        // 进入此if证明数据库操作发生了问题
        if (!result[0]) {
            throw new UnknownError();
        }
        return result;
    }

    // 走到这里证明，旧密码是错误的
    throw new ValidationError("账号或旧密码错误");
}